﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;

namespace ACC.Extensions.Utilities
{
    /// <summary>
    /// 获取网络日期时间
    /// </summary>
    /// <returns></returns>
    public static class SysDateTime
    {
        private static DateTime GetNetNow()
        {
            DateTime datetime = System.DateTime.Now;
            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            try
            {
                request = WebRequest.Create("https://www.baidu.com");
                request.Timeout = 3000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (WebResponse)request.GetResponse();
                headerCollection = response.Headers;
                if (headerCollection.AllKeys.Contains("Date"))
                {
                    datetime = Convert.ToDateTime(headerCollection["Date"]);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (request != null) request.Abort();
                if (response != null) response.Close();
                if (headerCollection != null) headerCollection.Clear();
            }
            return datetime;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SystemTime
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMiliseconds;
        }

        [DllImport("kernel32")]
        private static extern Int32 SetSystemTime(ref SystemTime time);

        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SystemTime sysTime);

        public static bool SetDate(DateTime dt)
        {
            bool flag = false;
            SystemTime sysTime = new SystemTime();

            sysTime.wYear = Convert.ToUInt16(dt.Year);
            sysTime.wMonth = Convert.ToUInt16(dt.Month);
            sysTime.wDay = Convert.ToUInt16(dt.Day);
            sysTime.wHour = Convert.ToUInt16(dt.Hour);
            sysTime.wMinute = Convert.ToUInt16(dt.Minute);
            sysTime.wSecond = Convert.ToUInt16(dt.Second);
            try
            {
                flag = SetLocalTime(ref sysTime);
            }
            catch (Exception e)
            {
                Log4Helper.Info("SetLocalTime函数执行异常" + e.Message);
            }

            return flag;
        }
    }
}
